package com.haitaoit.chengquan.module.center_service.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center_service.adapter.QualificationAdapter;
import com.haitaoit.chengquan.module.center_service.model.QualificationModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class QualificationActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.qualification_num)
    TextView qualification_num;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;


    private boolean isFrist = true;
    private int page = 1;
    private QualificationAdapter adapter;
    private List<String> listDetele = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_qualification);
        setTitle_V("资质介绍");
        setLeftShow(1, R.mipmap.left);
        setRightShow(0, R.string.qualification);
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pullrefreshscrollview.setPullLoadEnabled(false);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new QualificationAdapter(this);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        httpGetuser_qualification_introduced_list();
        listDetele = new ArrayList<>();
        qualification_num.setText(listDetele.size() + "");
        super.onResume();
    }

    @OnClick({R.id.right, R.id.qualification_detele})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right:// 添加资质
                startActivity(new Intent(QualificationActivity.this, QualificationAddActivity.class));
                break;
            case R.id.qualification_detele:// 删除
                if (listDetele.size() > 0) {
                    Dialog dlg = DialogUtil.showInfoDialog1(QualificationActivity.this, "提示",
                            "您确定要删除选中的资格证书吗？", "确定", "取消", new BackCall() {
                                public void deal(int which, Object... obj) {
                                    switch (which) {
                                        case R.id.confirm:// 确定
                                            httpGetdel_user_qualification_introduced(0, "");
                                            break;
                                    }
                                    super.deal(which);
                                }
                            });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                } else {
                    ToastUtils.showToast("请选择！");
                }
                break;
        }
        super.onClick(v);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            final int position = (Integer) obj[0];
            switch (which) {
                case R.id.quali_detele:
                    Dialog dlg = DialogUtil.showInfoDialog1(QualificationActivity.this, "提示",
                            "您确定要删除该资格证书吗？", "确定", "取消", new BackCall() {
                                public void deal(int which, Object... obj) {
                                    switch (which) {
                                        case R.id.confirm:// 确定
                                            httpGetdel_user_qualification_introduced(1, adapter.getList().get(position).getId());
                                            break;
                                    }
                                    super.deal(which);
                                }
                            });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                    break;
                case R.id.quali_ll:
                    if (listDetele.size() > 0) {
                        for (int i = 0; i < listDetele.size(); i++) {
                            if (listDetele.get(i).equals(adapter.getList().get(position).getId())) {
                                listDetele.remove(adapter.getList().get(position).getId());
                                qualification_num.setText(listDetele.size() + "");
                                return;
                            }
                        }
                        listDetele.add(adapter.getList().get(position).getId());
                    } else {
                        listDetele.add(adapter.getList().get(position).getId());
                    }
                    qualification_num.setText(listDetele.size() + "");
                    break;
            }
            super.deal(which, obj);
        }
    };

    private void httpGetuser_qualification_introduced_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_qualification_introduced_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<QualificationModel> new_list = new ArrayList<QualificationModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<QualificationModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<QualificationModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<QualificationModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<QualificationModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void httpGetdel_user_qualification_introduced(int type, String id) {
        String ids = "";
        if (type == 1) {// 单个删除
            ids = id;
        } else {// 多个删除
            for (int i = 0; i < listDetele.size(); i++) {
                ids = ids + listDetele.get(i) + ",";
            }
            ids = ids.substring(0, ids.length() - 1);
        }
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("ids", ids));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("ids", ids);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdel_user_qualification_introduced, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            listDetele = new ArrayList<>();
                            qualification_num.setText(listDetele.size() + "");
                            httpGetuser_qualification_introduced_list();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
    }
}
